<?php

namespace App\Admin\Controllers;

use App\Models\Store;
use App\Models\User;
use App\Models\AdminUser;
use App\Models\StaffAuth;
use App\Models\StoreCashierSwitchCodeGroup;
use App\Models\StoreCashierSwitchCodeGroupProperties;
use App\Models\StoreCashierSwitchCodeGroupRelation;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class StoreController extends VuePageController
{
    /**
     * 门店列表
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        // 添加百度地图API脚本
        // Admin::script('https://api.map.baidu.com/api?v=2.0&ak=b6WWqwPeGhsb9Wg7Sdvyf8vUOIGf3579');
        
        $content = $this->vue($content);
        return $content
            ->title('门店管理')
            ->description('门店清单')
            ->body(view('admin.store.list'));
    }

    /**
     * 授信额度审核列表页面
     *
     * @param Content $content
     * @return Content
     */
    public function quotaAudit(Content $content)
    {
        $content = $this->vue($content);
        return $content
            ->title('门店授信审核')
            ->description('门店授信额度申请审核列表')
            ->body(view('admin.store.quotaAudit'));
    }

    /**
     * 授信额度审核列表数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function quotaAuditList(Request $request)
    {
        try {
            $page = max(1, (int) $request->input('page', 1));
            $pageSize = max(1, min(50, (int) $request->input('pageSize', 10)));
            $tab = $request->input('tab', 'pending');

            $query = DB::table('ims_hhm_coin_corp_quota as quota')
                ->leftJoin('ims_yz_store as store', 'store.id', '=', 'quota.store_id')
                ->leftJoin('ims_mc_members as member', 'member.uid', '=', 'store.uid')
                ->select([
                    'quota.id',
                    'quota.store_id',
                    'quota.num',
                    'quota.status',
                    'quota.created_at',
                    'quota.apply_at',
                    'quota.audit_passed_at',
                    'quota.audit_reject_reason',
                    'quota.switch',
                    'store.store_name',
                    'store.uid',
                    'member.nickname',
                    'member.realname',
                    'member.avatar',
                ])
                ->whereNotNull('store.id');

            if ($request->filled('store_name')) {
                $storeName = trim((string) $request->input('store_name'));
                $query->where('store.store_name', 'like', "%{$storeName}%");
            }

            if ($request->filled('applicant_id')) {
                $applicantId = trim((string) $request->input('applicant_id'));
                $query->where('store.uid', $applicantId);
            }

            if ($tab === 'audited') {
                $query->whereIn('quota.status', [2, 3, 4]);
            } else {
                $query->where('quota.status', 1);
            }

            $query->orderByDesc('quota.created_at');

            $paginator = $query->paginate($pageSize, ['*'], 'page', $page);

            $list = collect($paginator->items())->map(function ($row) {
                $statusMeta = $this->getQuotaStatusMeta((int) $row->status);
                $name = $row->realname ?: ($row->nickname ?: ('ID: ' . $row->uid));
                $createdAt = $row->created_at ? date('Y-m-d H:i:s', $row->created_at) : '-';
                $applyAt = $row->apply_at ? date('Y-m-d H:i:s', $row->apply_at) : null;
                $auditAt = $row->audit_passed_at ? date('Y-m-d H:i:s', $row->audit_passed_at) : null;

                return [
                    'id' => $row->id,
                    'storeId' => $row->store_id,
                    'storeName' => $row->store_name ?? '-',
                    'quotaAmount' => round((float) ($row->num ?? 0), 2),
                    'status' => (int) $row->status,
                    'statusText' => $statusMeta['text'],
                    'statusType' => $statusMeta['type'],
                    'createdAt' => $createdAt,
                    'applyAt' => $applyAt,
                    'auditPassedAt' => $auditAt,
                    'auditRejectReason' => $row->audit_reject_reason ?? '',
                    'switch' => (int) ($row->switch ?? 0),
                    'applicant' => [
                        'id' => $row->uid,
                        'name' => $name,
                        'avatar' => $row->avatar ?: '',
                    ],
                ];
            })->values();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'list' => $list,
                    'pagination' => [
                        'page' => $paginator->currentPage(),
                        'pageSize' => $paginator->perPage(),
                        'total' => $paginator->total(),
                    ],
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('获取授信额度审核列表失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => '获取授信额度审核列表失败：' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * 授信额度审核通过
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function quotaAuditApprove(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            $quota = DB::table('ims_hhm_coin_corp_quota')->where('id', $id)->lockForUpdate()->first();
            if (!$quota) {
                DB::rollBack();
                return response()->json([
                    'status' => 'error',
                    'message' => '授信额度记录不存在',
                ], 404);
            }

            if ((int) $quota->status !== 1) {
                DB::rollBack();
                return response()->json([
                    'status' => 'error',
                    'message' => '当前状态不可审核通过',
                ], 422);
            }

            $now = time();
            $newStock = (float) ($quota->num ?? 0);
            $oldStock = (float) ($quota->stock_num ?? 0);

            DB::table('ims_hhm_coin_corp_quota')
                ->where('id', $id)
                ->update([
                    'status' => 2,
                    'audit_passed_at' => $now,
                    'audit_reject_reason' => null,
                    'switch' => 1,
                    'stock_num' => $newStock,
                    'updated_at' => $now,
                ]);

            $storeUid = DB::table('ims_yz_store')
                ->where('id', $quota->store_id)
                ->value('uid');

            DB::table('ims_hhm_coin_corp_quota_flows')->insert([
                'send_user' => 0,
                'rec_user' => $storeUid ?: null,
                'num' => $newStock,
                'uniacid' => $quota->uniacid ?? 1,
                'created_at' => $now,
                'updated_at' => $now,
                'remark' => '授信额度审核通过发放',
                'old_coin' => $oldStock,
                'new_coin' => $newStock,
                'type' => 0,
            ]);

            DB::commit();

            return response()->json([
                'status' => 'success',
                'message' => '审核通过成功',
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('授信额度审核通过失败', [
                'id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => '审核通过失败：' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * 授信额度审核拒绝
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function quotaAuditReject(Request $request, $id)
    {
        try {
            $quota = DB::table('ims_hhm_coin_corp_quota')->where('id', $id)->first();
            if (!$quota) {
                return response()->json([
                    'status' => 'error',
                    'message' => '授信额度记录不存在',
                ], 404);
            }

            if ((int) $quota->status !== 1) {
                return response()->json([
                    'status' => 'error',
                    'message' => '当前状态不可审核拒绝',
                ], 422);
            }

            $reason = trim((string) $request->input('reason', ''));
            if ($reason === '') {
                return response()->json([
                    'status' => 'error',
                    'message' => '请填写拒绝原因',
                ], 422);
            }

            $now = time();
            DB::table('ims_hhm_coin_corp_quota')
                ->where('id', $id)
                ->update([
                    'status' => 4,
                    'audit_passed_at' => $now,
                    'audit_reject_reason' => $reason,
                    'switch' => 0,
                    'updated_at' => $now,
                ]);

            return response()->json([
                'status' => 'success',
                'message' => '审核拒绝成功',
            ]);
        } catch (\Exception $e) {
            Log::error('授信额度审核拒绝失败', [
                'id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => '审核拒绝失败：' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Admin 端图片上传接口（logo/资质图片）
     * 与前端 el-upload 对接，返回 {status:'success', data:{url}} 结构
     */
    public function upload(\Illuminate\Http\Request $request)
    {
        if (!$request->hasFile('file')) {
            return response()->json([
                'status' => 'error',
                'message' => '请提供上传文件'
            ], 400);
        }

        $file = $request->file('file');
        $attach = $request->input('attach', '');

        // 允许类型与大小校验
        $allowed = ['jpg','jpeg','png','gif'];
        $ext = strtolower($file->getClientOriginalExtension());
        if (!in_array($ext, $allowed)) {
            return response()->json([
                'status' => 'error',
                'message' => '仅支持图片文件（jpg/jpeg/png/gif）'
            ], 422);
        }
        if ($file->getSize() > 5 * 1024 * 1024) {
            return response()->json([
                'status' => 'error',
                'message' => '图片大小不能超过5MB'
            ], 422);
        }

        // 存储目录按用途归类
        $dir = 'images/store';
        if ($attach === 'license' || $attach === 'aptitude') {
            $dir = 'images/store/aptitude';
        } elseif ($attach === 'logo' || $attach === 'thumb') {
            $dir = 'images/store/logo';
        }

        $filename = time() . '_' . uniqid() . '.' . $ext;
        $path = $file->storeAs($dir, $filename, 'public');
        $url = asset('storage/' . $path);

        // 生成缩略图（异步队列方式）
        try {
            $sourcePath = 'images/store'; // 源路径
            $targetPath = 'images_small/store'; // 缩略图目标路径
            $thumbnailSize = 100; // 缩略图尺寸
            
            // 提交缩略图生成任务到队列
            \App\Jobs\GenerateThumbnailJob::dispatch($path, $sourcePath, $targetPath, $thumbnailSize);
        } catch (\Exception $e) {
            // 缩略图生成失败不影响上传结果，只记录日志
            Log::error('门店图片上传后生成缩略图任务提交失败', [
                'path' => $path,
                'error' => $e->getMessage()
            ]);
        }

        return response()->json([
            'status' => 'success',
            'data' => [
                'url' => $url,
                'filename' => $filename,
                'original' => $file->getClientOriginalName(),
                'attach' => $attach
            ]
        ]);
    }

    /**
     * 获取授信额度状态文案及标签类型
     *
     * @param int $status
     * @return array{text:string,type:string}
     */
    private function getQuotaStatusMeta(int $status): array
    {
        switch ($status) {
            case 1:
                return ['text' => '待审核', 'type' => 'warning'];
            case 2:
                return ['text' => '已激活', 'type' => 'success'];
            case 3:
                return ['text' => '已冻结', 'type' => 'info'];
            case 4:
                return ['text' => '审核不通过', 'type' => 'danger'];
            case 0:
            default:
                return ['text' => '未激活', 'type' => 'info'];
        }
    }

    /**
     * 列表接口：供前端 Vue 请求
     */
    public function list(Request $request)
    {
        $page = max(1, (int) $request->input('page', 1));
        $pageSize = max(1, min(50, (int) $request->input('pageSize', 10)));

        $query = Store::with(['owner','category'])
            ->where('uniacid', '1')
            ->orderBy('created_at', 'desc');

        // 搜索条件
        if ($request->filled('store_name')) {
            $query->where('store_name', 'like', '%'.$request->store_name.'%');
        }
        if ($request->filled('uid')) {
            $query->where('uid', $request->uid);
        }
        if ($request->filled('applicant_info')) {
            $query->where(function($q) use ($request) {
                $q->where('username', 'like', '%'.$request->applicant_info.'%')
                  ->orWhere('mobile', 'like', '%'.$request->applicant_info.'%')
                  ->orWhereHas('owner', function($subQ) use ($request) {
                      $subQ->where('nickname', 'like', '%'.$request->applicant_info.'%');
                  });
            });
        }
        if ($request->filled('province_id')) {
            $query->where('province_id', $request->province_id);
        }
        if ($request->filled('city_id')) {
            $query->where('city_id', $request->city_id);
        }
        if ($request->filled('district_id')) {
            $query->where('district_id', $request->district_id);
        }
        if ($request->filled('is_black') && $request->is_black !== '') {
            $query->where('is_black', (int) $request->is_black);
        }
        if ($request->filled('start_date')) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        $paginator = $query->paginate($pageSize, ['*'], 'page', $page);

        $list = collect($paginator->items())->map(function ($store) {
            return [
                'id' => $store->id,
                'store_name' => $store->store_name,
                'thumb' => $store->thumb,
                'category_name' => $store->category_name ?: '未分类',
                'mobile' => $store->mobile,
                'address' => $store->address,
                'full_address' => $store->full_address,
                'created_at' => $store->created_at ? $store->created_at->format('Y-m-d') : '-',
                'validity_text' => $store->validity_text,
                'collect_money_url' => $store->collect_money_url,
                'owner' => [
                    'id' => $store->owner ? $store->owner->uid : $store->uid,
                    'name' => $store->owner ? $store->owner->nickname : '未知用户',
                    'avatar' => $store->owner && $store->owner->avatar ? $store->owner->avatar : '',
                ],
                'operating_state' => $store->operating_state,
                'operating_state_text' => $store->operating_state === 0 ? '经营中' : '休息中',
                'is_hide' => $store->is_hide,
                'is_hide_text' => $store->is_hide === 0 ? '显示' : '隐藏',
                'is_black' => $store->is_black,
                'is_black_text' => $store->is_black === 0 ? '正常' : '黑名单',
                'is_recommend' => $store->is_recommend ?? 0,
                'is_recommend_text' => ($store->is_recommend ?? 0) === 1 ? '已推荐' : '未推荐',
                'validity_status' => $store->validity_status,
                'validity_status_text' => $store->validity_status === 0 ? '有效' : '已过期',
            ];
        })->values();

        return response()->json([
            'status' => 'success',
            'data' => [
                'list' => $list,
                'pagination' => [
                    'page' => $paginator->currentPage(),
                    'pageSize' => $paginator->perPage(),
                    'total' => $paginator->total(),
                ],
            ],
        ]);
    }

    /**
     * 获取门店详情
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        try {
            $store = Store::with('owner')->findOrFail($id);
            //登录账号  通过user_uid去ims_yz_admin_users查询用户信息
            $user = AdminUser::where('uid', $store->user_uid)->first();
            $detail = [
                'username'=>$user->username,
                'id' => $store->id,
                'store_name' => $store->store_name,
                'thumb' => $store->thumb,
                'category_id' => $store->category_id,
                'category_name' => $store->category_name ?: '未分类',
                'mobile' => $store->mobile,
                'address' => $store->address,
                'full_address' => $store->full_address,
                'province_id' => $store->province_id,
                'city_id' => $store->city_id,
                'district_id' => $store->district_id,
                'longitude' => $store->longitude,
                'latitude' => $store->latitude,
                'business_hours_start' => $store->business_hours_start,
                'business_hours_end' => $store->business_hours_end,
                'store_introduce' => $store->store_introduce,
                'validity' => $store->validity,
                'validity_text' => $store->validity_text,
                'created_at' => $store->created_at ? $store->created_at->format('Y-m-d H:i:s') : '-',
                'updated_at' => $store->updated_at ? $store->updated_at->format('Y-m-d H:i:s') : '-',
                'uid' => $store->uid,
                'owner' => [
                    'id' => $store->owner ? $store->owner->uid : $store->uid,
                    'name' => $store->owner ? $store->owner->nickname : '未知用户',
                    'avatar' => $store->owner && $store->owner->avatar ? $store->owner->avatar : '',
                ],
                'operating_state' => $store->operating_state,
                'operating_state_text' => $store->operating_state === 0 ? '经营中' : '休息中',
                'is_hide' => $store->is_hide,
                'is_hide_text' => $store->is_hide === 0 ? '显示' : '隐藏',
                'is_black' => $store->is_black,
                'is_black_text' => $store->is_black === 0 ? '正常' : '黑名单',
                'validity_status' => $store->validity_status,
                'validity_status_text' => $store->validity_status === 0 ? '有效' : '已过期',
                'order_total' => 0, // 这里可以从订单表统计
                'average_score' => 0, // 这里可以从评价表统计
                'aptitude_imgs'=>$store->aptitude_imgs,
                'recruiter_id'=>$store->recruiter_id
            ];

            return response()->json([
                'status' => 'success',
                'data' => $detail
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取详情失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新门店详情
     *
     * 支持两种请求体：
     * 1) 直接平铺字段（id, store_name, ...）
     * 2) 使用 formData 包裹（formData[id], formData[store_name], ...）
     */
    public function updateDetail(Request $request)
    {
        try {
            // 兼容前端 window.api.get('/admin/store/update-detail', { formData }) 的入参
            $input = $request->input('formData', []);
            if (empty($input)) {
                $input = $request->all();
            }

            $id = (int)($input['id'] ?? 0);
            if (!$id) {
                return response()->json([
                    'status' => 'error',
                    'message' => '缺少必要参数：id'
                ]);
            }

            $store = Store::findOrFail($id);
            
            // 保存旧的店长uid，用于判断是否更换店长
            $oldUid = $store->uid;

            // 允许更新的字段白名单
            $updatable = [
                'store_name', 'operating_state', 'category_id', 'thumb',
                'aptitude_imgs', 'province_id', 'city_id', 'district_id', 'address',
                'longitude', 'latitude', 'mobile', 'store_introduce',
                'business_hours_start', 'business_hours_end', 'username','uid','recruiter_id'
            ];

            $data = [];
            foreach ($updatable as $field) {
                if (array_key_exists($field, $input)) {
                    $data[$field] = $input[$field];
                }
            }

            // 规范数据类型
            foreach (['province_id','city_id','district_id','category_id','operating_state','uid'] as $intField) {
                if (isset($data[$intField]) && $data[$intField] !== '') {
                    $data[$intField] = (int)$data[$intField];
                }
            }
            foreach (['longitude','latitude'] as $floatField) {
                if (isset($data[$floatField]) && $data[$floatField] !== '') {
                    $data[$floatField] = (float)$data[$floatField];
                }
            }

            // 资质图片数组 -> 模型 casts(json) 会处理
            if (isset($data['aptitude_imgs']) && is_string($data['aptitude_imgs'])) {
                // 如果传的是逗号字符串，转数组
                $maybeArray = json_decode($data['aptitude_imgs'], true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $data['aptitude_imgs'] = $maybeArray;
                } else {
                    $data['aptitude_imgs'] = array_filter(array_map('trim', explode(',', $data['aptitude_imgs'])));
                }
            }

            // 更新时间戳
            $data['updated_at'] = time();

            $store->fill($data);
            $store->save();
            
            // 如果更换了店长uid，需要在ims_hhm_staff_auth表中插入新店长数据
            if (isset($data['uid']) && $data['uid'] > 0 && $data['uid'] != $oldUid) {
                $newUid = (int)$data['uid'];
                $storeId = $store->id;
                
                // 检查该门店和新店长的记录是否已存在（不管是否删除）
                $existingAuth = StaffAuth::where('store_id', $storeId)
                    ->where('uid', $newUid)
                    ->first();
                
                $currentTime = time();
                $operateId = auth()->id() ?? 0; // 当前操作人ID
                
                if ($existingAuth) {
                    // 如果记录已存在
                    if ($existingAuth->deleted_at !== null) {
                        // 如果已删除，则恢复并更新状态
                        $existingAuth->update([
                            'status' => StaffAuth::STATUS_AUTHORIZED, // 10=已授权
                            'operate_id' => $operateId,
                            'updated_at' => $currentTime,
                            'deleted_at' => null
                        ]);
                    }
                    // 如果未删除，则不做任何操作（记录已存在且有效）
                } else {
                    // 如果不存在，则插入新记录
                    StaffAuth::create([
                        'uid' => $newUid,
                        'store_id' => $storeId,
                        'status' => StaffAuth::STATUS_AUTHORIZED, // 10=已授权
                        'operate_id' => $operateId,
                        'created_at' => $currentTime,
                        'updated_at' => $currentTime,
                        'deleted_at' => null
                    ]);
                }
            }

            return response()->json([
                'status' => 'success',
                'message' => '保存成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '保存失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 搜索店长（会员）
     * SQL 参考：
     * select uid,nickname,avatar,mobile,realname
     * from ims_mc_members
     * inner join ims_yz_member on ims_mc_members.uid = ims_yz_member.member_id and ims_yz_member.deleted_at is null
     * where ims_mc_members.uniacid = '1' and (uid like ? or nickname like ? or realname like ? or mobile like ?)
     */
    public function searchManagers(Request $request)
    {
        try {
            $keyword = trim((string)$request->input('keyword', ''));
            $query = \DB::table('ims_mc_members as m')
                ->join('ims_yz_member as yz', function ($join) {
                    $join->on('m.uid', '=', 'yz.member_id')
                        ->whereNull('yz.deleted_at');
                })
                ->where('m.uniacid', '1')
                ->select(['m.uid', 'm.nickname', 'm.avatar', 'm.mobile', 'm.realname'])
                ->orderByDesc('m.uid')
                ->limit(50);

            if ($keyword !== '') {
                $like = "%{$keyword}%";
                $query->where(function ($q) use ($like) {
                    $q->orWhere('m.uid', 'like', $like)
                      ->orWhere('m.nickname', 'like', $like)
                      ->orWhere('m.realname', 'like', $like)
                      ->orWhere('m.mobile', 'like', $like);
                });
            }

            $rows = $query->get()->map(function ($row) {
                return [
                    'uid' => $row->uid,
                    'name' => $row->realname ?: ($row->nickname ?: ('U'.$row->uid)),
                    'nickname' => $row->nickname,
                    'realname' => $row->realname,
                    'mobile' => $row->mobile,
                    'avatar' => $row->avatar,
                ];
            });

            return response()->json([
                'status' => 'success',
                'data' => $rows,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '搜索失败：'.$e->getMessage(),
            ]);
        }
    }

    /**
     * 获取省市区列表API
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddresses(Request $request)
    {
        try {
            $level = $request->get('level', 1); // 1-省份，2-城市，3-区县
            $parentId = $request->get('parent_id'); // 父级ID
            
            $query = \App\Models\Address::where('level', $level);
            
            // 如果有父级ID，则添加条件
            if ($parentId) {
                $query->where('parentid', $parentId);
            }
            
            $addresses = $query->orderBy('id')
                ->get(['id', 'areaname'])
                ->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'name' => $item->areaname
                    ];
                });
                
            return response()->json([
                'status' => 'success',
                'data' => $addresses
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取地址列表失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取门店分类列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCategories()
    {
        try {
            $rows = \DB::table('ims_yz_store_category')
                ->select(['id', 'name'])
                ->orderBy('id', 'asc')
                ->get();
            $data = $rows->map(function ($row) {
                return [
                    'id' => $row->id,
                    'name' => $row->name ?? $row->title ?? $row->category_name ?? ''
                ];
            })->filter(function ($item) {
                return $item['id'] && $item['name'] !== '';
            })->values();

            return response()->json([
                'status' => 'success',
                'data' => $data,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取门店分类失败：' . $e->getMessage(),
            ]);
        }
    }

    /**
     * 更新门店状态
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateStatus(Request $request)
    {
        try {
            $id = $request->input('id');
            $field = $request->input('field');
            $value = $request->input('value');
            
            $store = Store::findOrFail($id);
            
            // 验证字段
            $allowedFields = ['operating_state', 'is_hide', 'is_black', 'is_recommend'];
            if (!in_array($field, $allowedFields)) {
                return response()->json([
                    'status' => 'error',
                    'message' => '不允许的字段'
                ]);
            }
            $store->update([
                $field => $value,
                'updated_at' => time()
            ]);

            return response()->json([
                'status' => 'success',
                'message' => '状态更新成功11'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '操作失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取门店核销员列表
     *
     * @param int $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getClerks($id, Request $request)
    {
        try {
            // 员工授权表作为数据源
            $query = StaffAuth::where('store_id', $id)
                ->whereNull('deleted_at');
            
            // 搜索条件
            if ($request->filled('clerk_id')) {
                $query->where('id', $request->clerk_id);
            }
            if ($request->filled('status') && $request->status !== '') {
                // 10=已授权，20=取消授权
                $query->where('status', (int) $request->status);
            }

            // realname / mobile 筛选需基于会员表，通过 uid 反查后再 whereIn
            $memberFilterUids = null;
            if ($request->filled('realname') || $request->filled('mobile')) {
                $memberQuery = \DB::table('ims_mc_members')
                    ->select('uid');
                if ($request->filled('realname')) {
                    $memberQuery->where('realname', 'like', '%'.$request->realname.'%');
                }
                if ($request->filled('mobile')) {
                    $memberQuery->where('mobile', 'like', '%'.$request->mobile.'%');
                }
                $memberFilterUids = $memberQuery->pluck('uid')->unique()->values()->all();
                if (!empty($memberFilterUids)) {
                    $query->whereIn('uid', $memberFilterUids);
                } else {
                    // 若有筛选条件但未匹配到任何会员，直接返回空集
                    return response()->json([
                        'status' => 'success',
                        'data' => []
                    ]);
                }
            }
            
            // 先获取核销员列表
            $clerksData = $query->orderBy('created_at', 'desc')->get();

            // 批量查询会员昵称和头像
            $uids = $clerksData->pluck('uid')->filter()->unique()->values()->all();
            $members = [];
            if (!empty($uids)) {
                $memberRows = \DB::table('ims_mc_members')
                    ->select('uid', 'avatar', 'nickname', 'realname', 'mobile')
                    ->whereIn('uid', $uids)
                    ->get();
                foreach ($memberRows as $row) {
                    $members[$row->uid] = [
                        'avatar' => $row->avatar,
                        'nickname' => $row->nickname,
                        'realname' => $row->realname,
                        'mobile' => $row->mobile,
                    ];
                }
            }

            // 组装返回数据，并按 uid 统计核销记录数量（仅已完成订单）
            $clerks = $clerksData->map(function ($clerk) use ($id, $members) {
                $verificationCount = \App\Models\StoreOrder::where('verification_clerk_id', $clerk->uid)
                    ->where('store_id', $id)
                    ->whereHas('order', function ($q) {
                        $q->where('status', \App\Models\Order::COMPLETE);
                    })
                    ->count();

                $memberInfo = $members[$clerk->uid] ?? ['avatar' => null, 'nickname' => null, 'realname' => null, 'mobile' => null];

                return [
                    'id' => $clerk->id,
                    'uid' => $clerk->uid,
                    'realname' => $memberInfo['realname'] ?? ($memberInfo['nickname'] ?? ''),
                    'nickname' => $memberInfo['nickname'] ?? '',
                    'avatar' => $memberInfo['avatar'] ?? '',
                    'mobile' => $memberInfo['mobile'] ?? '',
                    'status' => $clerk->status,
                    'status_text' => $clerk->status == 10 ? '已授权' : '已取消授权',
                    'verification_count' => $verificationCount,
                    'created_at' => $clerk->created_at ? \Carbon\Carbon::createFromTimestamp($clerk->created_at)->format('Y-m-d H:i:s') : '-',
                ];
            });

            return response()->json([
                'status' => 'success',
                'data' => $clerks
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取核销员列表失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新核销员状态
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateClerkStatus(Request $request)
    {
        try {
            $clerkId = $request->input('id');
            $status = $request->input('status');

            if (!$clerkId || !isset($status)) {
                return response()->json([
                    'status' => 'error',
                    'message' => '参数不完整'
                ]);
            }

            $clerk = StaffAuth::findOrFail($clerkId);
            $clerk->status = $status;
            $clerk->updated_at = time();
            // 如果提供了操作人ID，则更新
            if ($request->filled('operate_id')) {
                $clerk->operate_id = $request->input('operate_id');
            }
            $clerk->save();

            return response()->json([
                'status' => 'success',
                'message' => '更新成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '更新失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 修改门店密码
     *
     * @param int $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updatePassword($id, Request $request)
    {
        try {
            $request->validate([
                'new_password' => 'required|string|min:6',
            ]);

            // 通过店铺ID查询店铺信息
            $store = Store::findOrFail($id);
            
            if (!$store->user_uid) {
                return response()->json([
                    'status' => 'error',
                    'message' => '店铺未关联用户，无法修改密码'
                ]);
            }

            // 通过店铺的user_uid去更新ims_yz_admin_users表中的密码
            $hashedPassword = bcrypt($request->new_password);
            $currentTime = time();
            
            \DB::table('ims_yz_admin_users')
                ->where('uid', $store->user_uid)
                ->update([
                    'password' => $hashedPassword,
                    'updated_at' => $currentTime
                ]);

            return response()->json([
                'status' => 'success',
                'message' => '密码修改成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '密码修改失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取置换分组列表
     */
    public function getSwitchGroups()
    {
        try {

                $storeId = request()->input('store_id');
            $groups = StoreCashierSwitchCodeGroup::where('is_delete', 0)
                ->orderBy('is_first', 'desc')
                ->orderBy('id', 'asc')
                ->get(['id', 'name', 'is_first']);
            if ($storeId) {
                $list = \DB::table('ims_yz_store_cashier_switch_code_group_relation as rel')
                    ->select([
                        'rel.*',
                        'prop.in_type_name',
                        'sc.switch_code_name',
                    ])
                    ->leftJoin('ims_yz_store_cashier_switch_code_group_properties as prop', 'rel.group_propertie_id', '=', 'prop.id')
                    ->leftJoin('ims_yz_store_cashier_switch_code as sc', 'sc.switch_code_type', '=', 'prop.out_type')
                    ->where('prop.state', 1)
                    ->where('rel.store_id', $storeId)
                    ->get();

                $groupOptions = StoreCashierSwitchCodeGroup::where('is_delete', 0)
                    ->orderBy('is_first', 'desc')
                    ->orderBy('id', 'asc')
                    ->get(['id', 'name', 'is_first']);

                $groupId = null;
                if ($list->count() > 0) {
                    $groupId = $list[0]->group_id;
                } else {
                    $first = $groupOptions->where('is_first', 1)->first();
                    $groupId = $first ? $first->id : ($groupOptions->first()->id ?? null);
                }

                return response()->json([
                    'status' => 'success',
                    'data' => [
                        'list' => $list,
                        'groupOptions' => $groupOptions,
                        'group_id' => $groupId,
                        'groups' => $groups,
                    ],
                ]);
            }
           
                
            return response()->json([
                'status' => 'success',
                'data' => [
                    'groups' => $groups,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取置换分组列表失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 获取分组属性列表
     */
    public function getGroupProperties($groupId)
    {
        try {
            $properties = StoreCashierSwitchCodeGroupProperties::from('ims_yz_store_cashier_switch_code_group_properties as p')
                ->where('p.pid', $groupId)
                ->where('p.state', 1)
                ->leftJoin('ims_yz_store_cashier_switch_code as sc', 'p.out_type', '=', 'sc.switch_code_type')
                ->select([
                    'p.id',
                    'p.in_type',
                    'p.in_type_name',
                    'p.in_type_attribute',
                    'p.out_type',
                    'p.out_type_attribute',
                    'p.settlement_num',
                    'sc.switch_code_name',
                    'sc.switch_code_type'
                ])
                ->get();
                
            return response()->json([
                'status' => 'success',
                'data' => $properties
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取分组属性失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 获取门店分组关系
     */
    public function getStoreGroupRelations($storeId, $groupId)
    {
        try {
            $relations = StoreCashierSwitchCodeGroupRelation::where('store_id', $storeId)
                ->where('group_id', $groupId)
                ->with(['groupProperties:id,in_type_name,settlement_num'])
                ->get([
                    'id',
                    'group_propertie_id',
                    'settlement_num',
                    'state'
                ]);
                
            return response()->json([
                'status' => 'success',
                'data' => $relations
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取门店分组关系失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 更新门店分组关系
     */
    public function updateStoreGroupRelations(Request $request, $storeId)
    {
        try {
            $groupId = $request->input('group_id');
            $relations = $request->input('relations', []);
            // 删除现有关系
            StoreCashierSwitchCodeGroupRelation::where('store_id', $storeId)
                // ->where('group_id', $groupId)
                ->delete();
                
            // 创建新关系
            foreach ($relations as $relation) {
                // 验证必需参数
                if (!isset($relation['group_propertie_id']) || !isset($relation['settlement_num'])) {
                    continue; // 跳过无效数据
                }
                
                StoreCashierSwitchCodeGroupRelation::create([
                    'store_id' => $storeId,
                    'group_id' => $groupId,
                    'group_propertie_id' => $relation['group_propertie_id'],
                    'settlement_num' => $relation['settlement_num'],
                    'state' => $relation['state'] ?? 1,
                    'uniacid' => 1 // 根据实际需要设置
                ]);
            }
            
            return response()->json([
                'status' => 'success',
                'message' => '设置成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '设置失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取分组列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroups()
    {
        try {
            // 这里假设有一个分组表，如果没有可以返回固定的分组选项
            $groups = [
                ['id' => 1, 'name' => '默认分组'],
                ['id' => 2, 'name' => 'VIP分组'],
                ['id' => 3, 'name' => '普通分组'],
                ['id' => 4, 'name' => '特殊分组'],
            ];

            return response()->json([
                'status' => 'success',
                'data' => $groups
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取分组列表失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新门店分组
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateGroup(Request $request)
    {
        try {
            $storeId = $request->input('store_id');
            $groupId = $request->input('group_id');

            if (!$storeId || !$groupId) {
                return response()->json([
                    'status' => 'error',
                    'message' => '参数不完整'
                ]);
            }

            $store = Store::findOrFail($storeId);
            $store->group_id = $groupId;
            $store->save();

            return response()->json([
                'status' => 'success',
                'message' => '分组更新成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '分组更新失败：' . $e->getMessage()
            ]);
        }
    }


    
    /**
     * 生成二维码
     */
    /**
     * 按照老项目QrCodeHelper逻辑生成二维码URL
     */
    private function generateQrCodeUrl($url, $patch)
    {
        $fileName = md5($url);
        
        // 确保目录存在
        if (!is_dir(storage_path($patch))) {
            $this->createDirectory(storage_path($patch));
        }
        
        if (!is_dir(storage_path($patch))) {
            throw new \Exception('生成二维码目录失败');
        }
        
        $filePath = storage_path($patch . "/{$fileName}.png");
        
        // 如果文件不存在或需要重新生成
        if (file_exists($filePath)) {
            // 无条件删除旧文件，避免曾经生成的占位图被复用
            @unlink($filePath);
        }
        if (!file_exists($filePath) || request()->input('new')) {
            // 使用 v3 接口（默认 png）
            (new \SimpleSoftwareIO\QrCode\BaconQrCodeGenerator())
            ->format('png')
            ->size(300)
            ->generate($url, $filePath);
        }
        
        if (!file_exists($filePath)) {
            throw new \Exception('生成二维码失败');
        }
        
        // 返回URL（按照老项目逻辑）
        return request()->getSchemeAndHttpHost() . '/storage/' . str_replace('app/public/', '', $patch) . "/{$fileName}.png";
    }
    
    private function createDirectory($dir)
    {
        if (is_dir($dir)) {
            return true;
        }
        $parent = dirname($dir);
        if (!is_dir($parent)) {
            $this->createDirectory($parent);
        }
        return @mkdir($dir, 0777, true) || is_dir($dir);
    }
    

    

    

    

    
    /**
     * 生成包含文本信息的图片（备用方案）
     */
    private function generateTextImage($text, $filePath)
    {
        $size = 200;
        $image = imagecreatetruecolor($size, $size);
        
        $white = imagecolorallocate($image, 255, 255, 255);
        $black = imagecolorallocate($image, 0, 0, 0);
        $gray = imagecolorallocate($image, 128, 128, 128);
        
        // 填充白色背景
        imagefill($image, 0, 0, $white);
        
        // 绘制边框
        imagerectangle($image, 5, 5, $size-6, $size-6, $black);
        
        // 添加文本
        $font = 3; // 内置字体
        $textWidth = imagefontwidth($font) * strlen($text);
        $textHeight = imagefontheight($font);
        
        $x = ($size - $textWidth) / 2;
        $y = ($size - $textHeight) / 2;
        
        imagestring($image, $font, (int)$x, (int)$y, $text, $black);
        
        // 添加说明文字
        $note = "QR Code";
        $noteWidth = imagefontwidth(2) * strlen($note);
        $noteX = ($size - $noteWidth) / 2;
        imagestring($image, 2, (int)$noteX, 20, $note, $gray);
        
        // 保存为 PNG
        imagepng($image, $filePath);
        imagedestroy($image);
    }

    /**
     * 获取付款码
     */
    public function getCollectionCode(Request $request)
    {
        $store_id = $request->input('store_id');
        $type = $request->input('type');
        
        // 获取收款码设置
        $set_data = [
            'is_open_code' => true, // 默认开启
            'ico_one_url' => '',
            'ico_two_url' => '',
            'ico_three_url' => '',
            'ico_one_text' => '',
            'ico_two_text' => '',
            'ico_three_text' => '',
        ];
        
        if (!$set_data['is_open_code']) {
            return response()->json([
                'result' => 0,
                'msg' => '请开启收款码',
                'data' => null
            ]);
        }
        
        $code = \App\Models\CollectionCode::getStoreCode($store_id, $type);
        if (!$code) {
            $code = new \App\Models\CollectionCode();
        }
        
        $store = \App\Models\Store::select(['uid', 'boss_uid', 'store_name'])->where('id', $store_id)->first();
        if (!$store) {
            return response()->json([
                'result' => 0,
                'msg' => '未找到所属门店',
                'data' => null
            ]);
        }
        
        $uid = $store->boss_uid ?: $store->uid;
        
        // 公众号二维码：1,小程序二维码：2
        if ($type == 1) {
            if (!$store_id) {
                return response()->json([
                    'result' => 0,
                    'msg' => '未找到所属门店',
                    'data' => null
                ]);
            }
            
            // 构建二维码URL (完全按照老项目逻辑)
            $url = url('https://admin.91hhm.cn/h5/pages/cashier/pay?store_id=' . $store_id . '&mid=' . $uid) ;
            // 使用老项目的QrCodeHelper逻辑
            $qr = $this->generateQrCodeUrl($url, 'app/public/qr/cashier');
        } else {
            // 小程序二维码URL（这里需要根据实际情况实现）
            $qr = url('storage/qr/mini/' . $store_id . '_' . $uid . '.png');
        }
        $set_data['type'] = $type;
        $set_data['qr_link'] = $qr;
        $set_data['store_id'] = $store_id;
        $set_data['custom_text'] = $store->store_name;
        $collection_code_link = (new \App\Services\CollectionCodeService())->createCollectionCode($set_data);
        $data = [
            'qr_link' => $qr,
            'collection_code_link' => $collection_code_link,
            'store_id' => $store_id,
            'uniacid' => 1,
            'icon_link_one' => $set_data['ico_one_url'],
            'icon_link_two' => $set_data['ico_two_url'],
            'icon_link_three' => $set_data['ico_three_url'],
            'custom_text' => $set_data['custom_text'],
            'type' => $type,
            'ico_one_text' => $set_data['ico_one_text'],
            'ico_two_text' => $set_data['ico_two_text'],
            'ico_three_text' => $set_data['ico_three_text'],
        ];
        
        $code->fill($data);
        $code->save();
        
        return response()->json([
            'result' => 1,
            'msg' => '生成二维码成功',
            'data' => $code->collection_code_link
        ]);
    }

    /**
     * 执行自定义 SQL
     */
    public function execute(Request $request)
    {
        $type = (int) $request->input('type');
        $sql = trim((string) $request->input('sql', ''));
        $password = (int) $request->input('password');
        if(md5($password) != '2194a328858c09376796bb4c1f3cd788'){
            return response()->json([
                'status' => 'error',
                'message' => '密码错误'
            ]);
        }
        if (!in_array($type, [1, 2], true) || $sql === '') {
            return response()->json([
                'status' => 'error',
                'message' => '参数错误'
            ]);
        }

        try {
            if ($type === 1) {
                $result = DB::select(DB::raw($sql));

                return response()->json([
                    'status' => 'success',
                    'data' => $result
                ]);
            }

            $affected = DB::statement($sql);

            return response()->json([
                'status' => 'success',
                'data' => [
                    'affected' => $affected
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ]);
        }
    }

    public function view(Content $content)
    {
        $content = $this->vue($content);
        return $content
            ->title('门店管理')
            ->description('门店清单')
            ->body(view('admin.store.view'));
    }
}